package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.dto.inst.InstAttrDTO;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.ILocalQueryScenePersonInfoService;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.IUnicomRegionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.ChannelKindDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.AssemblyAttrDtoUtils;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.ProdCateUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.dto.KiteAttrDTO;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.ICommonAttrHandler;
import com.iwhalecloud.bss.kite.web.service.accept.util.HandlerFactoryUtils;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.bss.order.base.consts.KeyValues;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <Description> 四类人信息初始化及修改 <br>
 *
 * @author zhu.zixin<br>
 * @version 1.0<br>
 * @taskId <br>
 * @date 2020-02-29 <br>
 * @since R9.0<br>
 */
@Service
public class PersonAttrDealService implements IPersonAttrDealService {

    @Autowired
    private ILocalQueryScenePersonInfoService queryScenePersonService;

    @Autowired
    private IUnicomRegionService unicomRegionService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void initAttr(String sceneInstId, String custId, boolean callInitMethod) {
        List<InstAttrDTO> attrConfigs = queryScenePersonService
            .listAllKiteConfigAttrs(sceneInstId, custId).getResultObject();
        List<CommonAttrVO> commonAttrList = AssemblyAttrDtoUtils.assemblyVO(attrConfigs);
        commonAttrList.forEach(commonAttrVO -> {
            if (KiteStringUtils.isNotBlank(commonAttrVO.getHandlerClass()) && callInitMethod) {
                ICommonAttrHandler commonAttrHandler = HandlerFactoryUtils.getHandler(commonAttrVO.getHandlerClass());
                if (commonAttrHandler != null) {
                    commonAttrHandler.init(commonAttrVO);
                }
            }
            setCommonAttr(sceneInstId, commonAttrVO);
        });
    }

    @Transactional(rollbackFor = Exception.class)
    public void initAttrList(List<CommonAttrVO> commonAttrList) {
        commonAttrList.forEach(commonAttrVO -> {
            if (StringUtils.isBlank(commonAttrVO.getValue())) {
                if (KiteStringUtils.isNotBlank(commonAttrVO.getHandlerClass())) {
                    ICommonAttrHandler commonAttrHandler = HandlerFactoryUtils.getHandler(commonAttrVO.getHandlerClass());
                    if (commonAttrHandler != null) {
                        commonAttrHandler.init(commonAttrVO);
                        return;
                    }

                }
            }
            setCommonAttr(KiteWebContext.getContext().getCurrentSceneInstId(), commonAttrVO);
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc,
                                     String moduleId) {
        //查询四类人的属性
        List<InstAttrDTO> commonAttrList = queryScenePersonService.listKiteConfigAttrsByModuleId(sceneInstId, moduleId)
            .getResultObject();
        List<InstAttrDTO> result = commonAttrList.stream()
            .filter(kiteAttrConfig -> KiteStringUtils.equals(fieldName, kiteAttrConfig.getFieldName()))
            .collect(Collectors.toList());
        if (!KiteListUtils.isEmpty(result)) {
            InstAttrDTO commonAttrVO = result.get(0);

            // 如果是下拉框，下拉值转义
            if (KiteStringUtils.equals(commonAttrVO.getAttrValueTypeId(), KeyValues.DROPDOWN)) {
                valueDesc = Optional.ofNullable(AttrValueCache.getAttrValue(commonAttrVO.getAttrId(), value))
                    .map(attrVal -> attrVal.getAttrValueDesc()).orElse(valueDesc);
            }

            if (KiteStringUtils.isNotBlank(commonAttrVO.getHandlerClass())) {
                ICommonAttrHandler commonAttrHandler = HandlerFactoryUtils.getHandler(commonAttrVO.getHandlerClass());
                if (commonAttrHandler != null) {
                    return commonAttrHandler.apply(sceneInstId, fieldName, value, valueDesc);
                }
            }

        }
//        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
//        List<KiteProdInst> kiteProdInstList = querySceneInstService.listProdInsts(sceneInstId);
//        if (KiteListUtils.isNotEmpty(kiteProdInstList)) {
//            for (KiteProdInst prodInst : kiteProdInstList) {
//                KiteAttr serviceLevelAttr = prodInst.getAttr("200003681");
//                if (serviceLevelAttr == null) {
//                    continue;
//                }
//                //如果平台服务级别是高级平台，然后附加产品-可付费套包不能选择
//                if ("100006417".equals(serviceLevelAttr.getValue()) && "T".equals(value) && "10004282"
//                    .equals(fieldName)) {
//                    ErrorConsts.BUSI_COMMON_ERROR.throwOut("平台服务级别为高级平台，附加产品的可付费套包不能选择");
//                }
//            }
//        }

        return setCommonAttr(sceneInstId, fieldName, value, valueDesc);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public DataResult<Boolean> apply(String sceneInstId, List<KiteAttrDTO> attrs) {
        //查询四类人的属性
        List<InstAttrDTO> commonAttrList = queryScenePersonService
            .listAllKiteConfigAttrs(sceneInstId, KiteWebContext. getContext().getCustId())
            .getResultObject();
        for (InstAttrDTO instAttrDTO : commonAttrList) {
            List<InstAttrDTO> result = commonAttrList.stream()
                .filter(kiteAttrConfig -> KiteStringUtils.equals(instAttrDTO.getFieldName(), kiteAttrConfig.getFieldName()))
                .collect(Collectors.toList());
            if (!KiteListUtils.isEmpty(result)) {
                InstAttrDTO commonAttrVO = result.get(0);
                // 如果是下拉框，下拉值转义
                if (KiteStringUtils.equals(commonAttrVO.getAttrValueTypeId(), KeyValues.DROPDOWN)) {
                    instAttrDTO.setValueDesc(Optional.ofNullable(AttrValueCache.getAttrValue(commonAttrVO.getAttrId(), instAttrDTO.getValue()))
                        .map(attrVal -> attrVal.getAttrValueDesc()).orElse(instAttrDTO.getValueDesc()));
                }
            }
        }
        dealPersonAttrsSpecial(sceneInstId, attrs);
        return setCommonAttrs(sceneInstId, attrs);
    }

    @Override
    public List<CommonAttrVO> getMoreByObjType(String sceneInstId, String objType) {
        //根据objType去加载更多属性
        List<InstAttrDTO> attrConfigs = queryScenePersonService.listKiteConfigAttrs(sceneInstId, objType)
            .getResultObject().stream().filter(instAttrDTO -> LocalKeyConsts.KITE_ATTR_CONFIG_SHOW_TYPE_M.equals(instAttrDTO.getShowType())).collect(Collectors.toList());
        List<CommonAttrVO> commonAttrList =  AssemblyAttrDtoUtils.assemblyVO(attrConfigs);
        return commonAttrList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public DataResult<Boolean> apply(KiteAttr attr , String sceneInstId, String fieldName,String  value, String valueDesc) {
        if (KiteStringUtils.isNotBlank(attr.getHandlerClass())) {
            ICommonAttrHandler commonAttrHandler = HandlerFactoryUtils.getHandler(attr.getHandlerClass());
            if (commonAttrHandler != null) {
                return commonAttrHandler.apply(sceneInstId, fieldName, value, valueDesc);
            }
        }
        return ErrorConsts.SUCCESS.getResult(true);
    }
    /**
     * 设置公共信息，判空
     * @param sceneInstId
     * @param commonAttrVO
     */
    private void setCommonAttr(String sceneInstId, CommonAttrVO commonAttrVO) {
        if (StringUtils.isNotBlank(commonAttrVO.getValue())) {
            setCommonAttr(sceneInstId, commonAttrVO.getFieldName(), commonAttrVO.getValue(), commonAttrVO.getValueDesc());
        }
    }

    /**
     * 设置公共信息,不做判空
     */
    private DataResult<Boolean> setCommonAttr(String sceneInstId, String fieldName, String value, String valueDesc) {
        return SpringUtil.getBean(IOperateSceneCommonService.class).setCommonAttrValue(sceneInstId,
            fieldName, value, valueDesc);
    }


    /**
     * 设置公共信息,不做判空
     */
    private DataResult<Boolean> setCommonAttrs(String sceneInstId, List<KiteAttrDTO> attrs) {
        return SpringUtil.getBean(IOperateSceneCommonService.class).setCommonAttrValues(sceneInstId, attrs);
    }

    private void dealPersonAttrsSpecial(String sceneInstId, List<KiteAttrDTO> attrs) {
        if (KiteListUtils.isEmpty(attrs)) {
            return;
        }
        KiteAttrDTO devChannelIdAttr = attrs.stream().filter(attr -> KiteStringUtils.equals(LocalKeyConsts.DEVPERSON_INFO_CHANNELID, attr.getFieldName())).findFirst().orElse(null);
        if (Objects.isNull(devChannelIdAttr)) {
            return;
        }
        // 获取总部直签渠道类型
        ChannelKindDTO parDirectKind = unicomRegionService.queryChannel().stream().findFirst().orElse(null);
        if (Objects.nonNull(parDirectKind)) {
            List<ChannelKindDTO> subDirectKinds = unicomRegionService.queryChannelByLevel(parDirectKind.getCodeValue());
            if (KiteListUtils.isNotEmpty(subDirectKinds)) {
                List<String> existChannels = subDirectKinds.stream().map(kind -> kind.getCodeValue()).collect(Collectors.toList());
                if (KiteListUtils.isNotEmpty(existChannels)) {
                    if (existChannels.contains(devChannelIdAttr.getValue())) {
                        operateSceneInstService.putExtParameter(sceneInstId, "isCenterDirectMark", "T");
                    } else {
                        operateSceneInstService.putExtParameter(sceneInstId, "isCenterDirectMark", "F");
                    }
                }
            }
        }
        //五大双新增渠道与发起方客户经理联动关系（接口还未改造）
        //dealPersonAttrsSpecialLine(sceneInstId, attrs);
    }

    private void dealPersonAttrsSpecialLine(String sceneInstId, List<KiteAttrDTO> attrs) {
        //五大双新增渠道与发起方客户经理联动关系
        String cateId = CuccPosServiceUtils.getCateId(sceneInstId, KiteWebContext.getContext().getCustId());
        if (KiteStringUtils.equalsAny(cateId, ProdCateUtil.getDoubleLineCateIdForArr())) {
            KiteAttrDTO devNameAttr = attrs.stream().filter(attr -> KiteStringUtils.equals(LocalKeyConsts.DEVPERSON_INFO_NAME, attr.getFieldName())).findFirst().orElse(null);
            KiteAttrDTO devTelAttr = attrs.stream().filter(attr -> KiteStringUtils.equals(LocalKeyConsts.DEVPERSON_INFO_TEL, attr.getFieldName())).findFirst().orElse(null);
            //MV 1、发展人信息：选择社会渠道时，要求CE端经营管理信息中“发展渠道”“发展人”变为必填；
            //2、发展人信息：选择自有渠道时，要求CE端经营管理信息中发展渠道、发展人根据
            if (KiteStringUtils.equalsAny(cateId, ProdCateUtil.getProdIdByCodeForArr(ProdCateUtil.MV_CODE, ProdCateUtil.GXCZ_CODE, ProdCateUtil.YTW_CODE))) {
                //发展人
                KiteAttr attr_2_0000130 = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.FIELD_NAME_2_0000130);
                //发展渠道
                KiteAttr attr_2_0000128 = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.FIELD_NAME_2_0000128);
                if (Objects.nonNull(attr_2_0000130) && Objects.nonNull(attr_2_0000128)) {
                    if (true) {
                        attr_2_0000130.setIsNull(KeyConsts.IFTRUE_F);
                        attr_2_0000128.setIsNull(KeyConsts.IFTRUE_F);
                    } else {
                        attr_2_0000130.setIsNull(KeyConsts.IFTRUE_T);
                        attr_2_0000128.setIsNull(KeyConsts.IFTRUE_T);
                        KiteAttrDTO devChannelNameAttr = attrs.stream().filter(attr -> KiteStringUtils.equals(LocalKeyConsts.DEVPERSON_INFO_CHANNELNAME, attr.getFieldName())).findFirst().orElse(null);
                        if (!Objects.isNull(devChannelNameAttr)) {
                            attr_2_0000128.setValue(devChannelNameAttr.getValue());
                            attr_2_0000128.setValueDesc(devChannelNameAttr.getValueDesc());
                        }
                        if (!Objects.isNull(devNameAttr)) {
                            attr_2_0000130.setValue(devNameAttr.getValue());
                            attr_2_0000130.setValueDesc(devNameAttr.getValueDesc());
                        }
                    }
                    operateSceneInstService.setCommonAttr(sceneInstId, attr_2_0000130);
                    operateSceneInstService.setCommonAttr(sceneInstId, attr_2_0000128);
                }
            }
            //互联网  1、发展人信息：选择社会渠道时，要求“发起方客户经理”“发起方客户经理联系电话”变为必填；
            //2、发展人信息：选择自有渠道时，发起方客户经理和联系电话根据发展人信息自动补全
            if (KiteStringUtils.equalsAny(cateId, ProdCateUtil.getProdIdByCodeForArr(ProdCateUtil.DIA_CODE))) {
                //发起方客户经理
                KiteAttr attr_2_0000213 = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.FIELD_NAME_2_0000213);
                //发起方客户经理联系电话
                KiteAttr attr_200002520 = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.FIELD_NAME_200002520);
                if (Objects.nonNull(attr_2_0000213) && Objects.nonNull(attr_200002520)) {
                    if (true) {
                        attr_2_0000213.setIsNull(KeyConsts.IFTRUE_F);
                        attr_200002520.setIsNull(KeyConsts.IFTRUE_F);
                    } else {
                        attr_2_0000213.setIsNull(KeyConsts.IFTRUE_T);
                        attr_200002520.setIsNull(KeyConsts.IFTRUE_T);
                        if (!Objects.isNull(devTelAttr)) {
                            attr_200002520.setValue(devTelAttr.getValue());
                            attr_200002520.setValueDesc(devTelAttr.getValueDesc());
                        }
                        if (!Objects.isNull(devNameAttr)) {
                            attr_2_0000213.setValue(devNameAttr.getValue());
                            attr_2_0000213.setValueDesc(devNameAttr.getValueDesc());
                        }
                    }
                    operateSceneInstService.setCommonAttr(sceneInstId, attr_2_0000213);
                    operateSceneInstService.setCommonAttr(sceneInstId, attr_200002520);
                }
            }
            //以太网、光纤出租、SDH  1、发展人信息：选择社会渠道时，要求A端经营管理信息中“A端客户经理”“A端客户经理联系电话”必填；
            //2、发展人信息：选择自有渠道时，要求A端经营管理信息中A端客户经理和联系电话根据发展人信息自动补全
            if (KiteStringUtils.equalsAny(cateId, ProdCateUtil.getProdIdByCodeForArr(ProdCateUtil.SDH_CODE, ProdCateUtil.GXCZ_CODE, ProdCateUtil.YTW_CODE))) {
                //A端客户经理
                KiteAttr attr_2_0000126 = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.FIELD_NAME_2_0000126);
                //A端客户经理联系电话
                KiteAttr attr_2_0000136 = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.FIELD_NAME_2_0000136);
                if (Objects.nonNull(attr_2_0000126) && Objects.nonNull(attr_2_0000136)) {
                    if (true) {
                        attr_2_0000126.setIsNull(KeyConsts.IFTRUE_F);
                        attr_2_0000136.setIsNull(KeyConsts.IFTRUE_F);
                    } else {
                        attr_2_0000126.setIsNull(KeyConsts.IFTRUE_T);
                        attr_2_0000136.setIsNull(KeyConsts.IFTRUE_T);
                        if (!Objects.isNull(devTelAttr)) {
                            attr_2_0000136.setValue(devTelAttr.getValue());
                            attr_2_0000136.setValueDesc(devTelAttr.getValueDesc());
                        }
                        if (!Objects.isNull(devNameAttr)) {
                            attr_2_0000126.setValue(devNameAttr.getValue());
                            attr_2_0000126.setValueDesc(devNameAttr.getValueDesc());
                        }
                    }
                    operateSceneInstService.setCommonAttr(sceneInstId, attr_2_0000126);
                    operateSceneInstService.setCommonAttr(sceneInstId, attr_2_0000136);
                }
            }
        }
    }
}
